<template>
  <el-container style="height: 600px; border: 1px solid #eee">
    <el-aside>
      <el-tree
        :props="props"
        :load="loadNode"
        lazy
      />
    </el-aside>
    <!-- 增加资源的弹出框 -->
    <el-dialog title="新增商品类型" :visible.sync="addFormVisible">
      <el-form :model="addForm">
        <!-- 商品类型的序号 -->
        <el-form-item
          :label="tableFomat[0].label"
          :label-width="formLabelWidth"
          style="display:inline-block"
        >
          <el-input v-model="addForm.sort" type="number" autocomplete="off" />
        </el-form-item>
        <!-- 商品类型的名称 -->
        <el-form-item
          :label="tableFomat[1].label"
          :label-width="formLabelWidth"
          style="display:inline-block"
        >
          <el-input v-model="addForm.type_name" autocomplete="off" placeholder="请输入商品类型名称" />
        </el-form-item>
        <!-- 商品类型的层级 -->
        <el-form-item
          :label="tableFomat[2].label"
          :label-width="formLabelWidth"
          style="display:inline-block"
        >
          <el-input
            v-model="addForm.level"
            type="number"
            min="1"
            max="3"
            autocomplete="off"
            @input="numRange(addForm)"
          />
        </el-form-item>
        <br>
        <!-- 商品类型的父亲节点 -->
        <el-form-item
          :label="tableFomat[3].label"
          :label-width="formLabelWidth"
          style="display:inline-block"
        >
          <el-select
            v-model="addForm.parent_id"
            placeholder="选择父亲节点类型"
            :disabled="addForm.level == 1 ? true : false"
            filterable
          >
            <el-option
              v-for="item in addFormParentIdFilter"
              :key="item._id"
              :label="item.type_name"
              :value="item._id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取 消</el-button>
        <el-button type="primary" :disabled="addConfirm" @click="addGoodsType()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑资源的弹出框 -->
    <el-dialog title="修改商品类型" :visible.sync="updateFormVisible">
      <el-form :model="updateForm">
        <el-form-item
          :label="tableFomat[0].label"
          :label-width="formLabelWidth"
          style="display:inline-block"
        >
          <el-input v-model="updateForm.sort" type="number" autocomplete="off" />
        </el-form-item>
        <el-form-item
          :label="tableFomat[1].label"
          :label-width="formLabelWidth"
          style="display:inline-block"
        >
          <el-input v-model="updateForm.type_name" autocomplete="off" placeholder="请输入商品类型名称" />
        </el-form-item>
        <el-form-item
          :label="tableFomat[2].label"
          :label-width="formLabelWidth"
          style="display:inline-block"
        >
          <el-input
            v-model="updateForm.level"
            type="number"
            min="1"
            max="3"
            autocomplete="off"
            @input="numRange(updateForm)"
          />
        </el-form-item>
        <br>
        <el-form-item
          :label="tableFomat[3].label"
          :label-width="formLabelWidth"
          style="display:inline-block"
        >
          <el-select
            v-model="updateForm.parent_id"
            placeholder="选择父亲节点类型"
            :disabled="updateForm.level == 1 ? true : false"
            filterable
          >
            <el-option
              v-for="item in updateFormParentIdFilter"
              :key="item._id"
              :label="item.type_name"
              :value="item._id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateFormVisible = false">取 消</el-button>
        <el-button type="primary" :disabled="updateConfirm" @click="updateGoodsType()">确 定</el-button>
      </div>
    </el-dialog>
    <el-container>
      <!-- 搜索区 -->
      <el-header>
        <el-input v-model="search.input" placeholder="类型名称" style="width:300px;" />
        <el-select v-model="search.selectValue" clearable placeholder="层级">
          <el-option
            v-for="item in search.options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" icon="el-icon-search">搜索</el-button>
      </el-header>

      <!-- 功能区 -->
      <el-main style="height:600px;">
        <el-row>
          <el-button type="success" size="mini" @click="addFormVisible = true">增加</el-button>
          <el-button type="primary" size="mini" @click="Edit()">编辑</el-button>
          <el-button size="mini" type="danger" @click="deletes()">删除</el-button>
        </el-row>
        <!-- 表格 组件 -->
        <datatable
          :table-fomat="tableFomat"
          :table-data="searchFilter"
          :total="tableData.length"
          @handleEdit="handleEdit"
          @handleDelete="handleDelete"
          @handleSelectionChange="handleSelectionChange"
        >
          <el-table-column label="是否有孩子节点" width="120">
            <template slot-scope="scope">
              {{ scope.row.is_has_child == 0 ? '无' : '有' }}
            </template>
          </el-table-column>
        </datatable>
      </el-main>
    </el-container>
  </el-container>
</template>
<style>
/* 容器头部 和  */
.el-header {
  line-height: 60px;
}
.el-aside {
  width: 200px !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  color: #333;
  background-color: white;
}
</style>
<script>
import datatable from '@/views/my-views/components/table'
import goods from '@/sql/table-field/index'
import { tsFormatTime } from '@/tools/util'
import { mapGetters } from 'vuex'
export default {
  name: 'GoodsCategory',
  components: {
    datatable
  },
  data() {
    return {
      // 树形控件数据
      props: {
        label: 'label',
        children: 'zones',
        isLeaf: 'leaf'
      },
      // 解决notice通知栏覆盖问题
      notifyPromise: Promise.resolve(),

      systemName: '商品分类',
      // 搜索输入框的值
      search: {
        input: '',
        selectValue: '',
        options: [
          {
            value: 1,
            label: '1'
          },
          {
            value: 2,
            label: '2'
          },
          {
            value: 3,
            label: '3'
          }
        ]
      },

      // 表格数据

      // 表格显示格式(列名以及列对应显示的数据)
      tableFomat: goods.goods_type,
      // 表格数据
      tableData: [],
      // 当前表格选中的数据
      multipleSelection: [],

      // 增加的弹出框设置
      addFormVisible: false,
      addForm: {
        parent_is_has_child: 1,
        parent_id: '',
        type_name: '',
        sort: 1,
        level: 1
      },
      formLabelWidth: '120px',

      // 修改资源的弹出框设置
      updateFormVisible: false,
      updateForm: {
        _id: '',
        parent_id: '',
        type_name: '',
        sort: 1,
        level: 1
      },

      // 删除商品类型的字段
      deleteForm: {
        parent_is_has_child: 0,
        parent_id: '',
        _id: '',
        type_name: ''
      }
    }
  },
  computed: {
    // 从store中的getters中获取数据(store/getters.js)
    ...mapGetters(['goodsTypeList']),
    // 搜索框
    searchFilter() {
      if (this.search.input !== '' || this.search.selectValue !== '') {
        if (this.search.input !== '' && this.search.selectValue === '') {
          let tableData = []
          tableData = this.tableData.filter(res => {
            return res.type_name.indexOf(this.search.input) > -1
          })
          return tableData
        } else if (this.search.input === '' && this.search.selectValue !== '') {
          let tableData = []
          tableData = this.tableData.filter(res => {
            return res.level === this.search.selectValue
          })
          return tableData
        } else {
          let tableData = []
          tableData = this.tableData.filter(res => {
            return (
              res.level === this.search.selectValue &&
              res.type_name.indexOf(this.search.input) > -1
            )
          })
          return tableData
        }
      } else {
        return this.tableData
      }
    },
    // 添加弹出框父亲节点的过滤
    addFormParentIdFilter() {
      return this.tableData.filter(
        item => item.level + 1 === Number(this.addForm.level)
      )
    },
    // 修改弹出框父亲节点的过滤
    updateFormParentIdFilter() {
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      return this.tableData.filter(
        item => item.level + 1 === Number(this.updateForm.level)
      )
    },
    // 添加确认框监听
    addConfirm() {
      if (
        (this.addForm.parent_id === '' && this.addForm.level != 1) ||
        this.addForm.type_name === '' ||
        this.addForm.sort === '' ||
        this.addForm.level === ''
      ) {
        return true
      } else {
        return false
      }
    },
    // 修改确认框监听
    updateConfirm() {
      if (
        (this.updateForm.parent_id === '' && this.updateForm.level != 1) ||
        this.updateForm.type_name === '' ||
        this.updateForm.sort === '' ||
        this.updateForm.level === ''
      ) {
        return true
      } else {
        return false
      }
    }
  },
  mounted() {
    // 如果state中有数据则从state中读取
    if (this.goodsTypeList.length !== 0) {
      // 使用缓存
      this.tableData = this.goodsTypeList
    } else {
      // 获取商品类型列表
      this.getGoodsTypes()
    }
  },
  methods: {
    // 树形控件数据加载
    loadNode(node, resolve) {
      const { level } = node
      setTimeout(() => {
        let tableData = []
        this.$store
          .dispatch('getGoodsTypes')
          .then(res => {
            if (res.errcode !== 0) {
              if (res.errcode === 42001) {
                this.$notify.error({
                  title: 'Access_token失效,请重新刷登录获取',
                  message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                  duration: 0
                })
              } else {
                this.$notify.error({
                  title: '获取商品类型列表失败',
                  message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                  duration: 0
                })
              }
            } else {
              tableData = JSON.parse(res.resp_data).data.list
              console.log(tableData)
              if (level === 0) {
                const nodes = tableData
                  .filter(res => res.level === 1)
                  .map(item => ({
                    value: item._id,
                    label: item.type_name,
                    leaf: item.is_has_child === 0
                  }))
                // 通过调用resolve将子节点数据返回，通知组件数据加载完成
                resolve(nodes)
              }
              if (level === 1) {
                const nodes = tableData
                  .filter(
                    res => res.level === 2 && res.parent_id === node.data.value
                  )
                  .map(item => ({
                    value: item._id,
                    label: item.type_name,
                    leaf: item.is_has_child === 0
                  }))
                // 通过调用resolve将子节点数据返回，通知组件数据加载完成
                resolve(nodes)
              }
              if (level === 2) {
                const nodes = tableData
                  .filter(
                    res => res.level === 3 && res.parent_id === node.data.value
                  )
                  .map(item => ({
                    value: item._id,
                    label: item.type_name,
                    leaf: item.is_has_child === 0
                  }))
                // 通过调用resolve将子节点数据返回，通知组件数据加载完成
                resolve(nodes)
              }
            }
          })
          .catch(err => {
            console.log('获取商品的代码逻辑错误', err)
          })
      }, 1000)
    },
    // tip提示方法
    tipformat(res, type, type_name) {
      if (res.errcode !== 0) {
        this.notifyPromise = this.notifyPromise
          .then(this.$nextTick)
          .then(() => {
            this.$notify.error({
              title: `${type}商品类型失败`,
              message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
              duration: 0
            })
          })
      } else {
        this.notifyPromise = this.notifyPromise
          .then(this.$nextTick)
          .then(() => {
            this.$notify({
              title: `${type}商品类型成功`,
              message: `${type_name}--商品类型${type}成功`,
              type: 'success',
              duration: 6000
            })
          })
        // 重新从数据库获取数据
        this.getGoodsTypes()
      }
    },
    // 修改商品类型
    updateGoodsType() {
      this.updateFormVisible = false
      this.$store
        .dispatch('updateGoodsType', this.updateForm)
        .then(res => {
          const type = '修改'
          this.tipformat(res, type, this.updateForm.type_name)
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 数据库数据转换为前端显示数据格式
    dataBaseToFormData(value) {
      value.create_time = tsFormatTime(
        value.create_time,
        'Y-M-D h:m:s'
      )
      value.update_time = tsFormatTime(
        value.update_time,
        'Y-M-D h:m:s'
      )
      return value
    },
    // 获取商品类型的方法
    getGoodsTypes() {
      this.$store
        .dispatch('getGoodsTypes')
        .then(res => {
          if (res.errcode !== 0) {
            if (res.errcode === 42001) {
              this.$notify.error({
                title: 'Access_token失效,请重新刷登录获取',
                message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                duration: 0
              })
            } else {
              this.$notify.error({
                title: '获取商品类型列表失败',
                message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                duration: 0
              })
            }
          } else {
            this.tableData = JSON.parse(res.resp_data).data.list
            this.tableData.map(res => {
              this.dataBaseToFormData(res)
            })
            this.$store.commit('setGoodsTypeList', this.tableData)
          }
        })
        .catch(err => {
          console.log('获取商品类型的代码逻辑错误', err)
        })
    },
    // 监听数字范围
    numRange(formdata) {
      if ((formdata.level < 1 || formdata.level > 3) && formdata.level !== '') {
        formdata.level = ''
        this.$message('层级的输入范围为1~3')
      }
    },
    // 添加商品类型
    addGoodsType() {
      if (
        this.tableData.find(res => this.addForm.type_name === res.type_name) !==
        undefined
      ) {
        this.$notify({
          title: `该商品类型已存在`,
          type: 'warning'
        })
      } else {
        this.addFormVisible = false
        this.$store
          .dispatch('addGoodsType', this.addForm)
          .then(res => {
            // 消息提示规范
            const type = '添加'
            this.tipformat(res, type, this.addForm.type_name)
          })
          .catch(err => {
            console.log('添加商品类型失败', err)
          })
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 页码
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
    },
    // 实时更新是否有孩子节点
    updateChild(deleteForm) {
      // 延时是为了table更新
      setTimeout(() => {
        if (deleteForm.length >= 1) {
          deleteForm.forEach(res => {
            if (res.parent_id !== '') {
              const ele = this.tableData.find(item => res.parent_id === item.parent_id)
              if (ele === undefined) {
                const item = {}
                item.parent_id = res.parent_id
                item.parent_is_has_child = 0
                this.$store.dispatch('updateGoodsTypeChild', item)
              }
            }
          })
        } else {
          if (deleteForm.parent_id !== '') {
            const ele = this.tableData.find(item => deleteForm.parent_id === item.parent_id)
            if (ele === undefined) {
              this.$store.dispatch('updateGoodsTypeChild', deleteForm)
            }
          }
        }
      }, 3000)
    },
    // 每列的编辑
    handleEdit(index, row) {
      this.updateFormVisible = true
      this.updateForm._id = row._id
      this.updateForm.sort = row.sort
      this.updateForm.type_name = row.type_name
      this.updateForm.level = row.level
      this.updateForm.parent_id = row.parent_id
    },
    // 每列的删除
    handleDelete(index, row) {
      this.deleteForm.parent_id = row.parent_id
      this.deleteForm._id = row._id
      this.deleteForm.type_name = row.type_name
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$store
            .dispatch('deleteGoodsTypeById', this.deleteForm)
            .then(res => {
              const type = '删除'
              this.tipformat(res, type, row.type_name)
              this.updateChild(this.deleteForm)
            })
            // eslint-disable-next-line handle-callback-err
            .catch(err => {
              this.$message.error({
                type: 'info',
                message: '删除商品类型失败',
                duration: 0
              })
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 头部的编辑
    Edit() {
      if (this.multipleSelection.length === 1) {
        this.updateFormVisible = true
        this.updateForm._id = this.multipleSelection[0]._id
        this.updateForm.sort = this.multipleSelection[0].sort
        this.updateForm.level = this.multipleSelection[0].level
        this.updateForm.type_name = this.multipleSelection[0].type_name
        this.updateForm.parent_id = this.multipleSelection[0].parent_id
      } else {
        this.$message('你有且必须选择一条数据')
      }
    },

    // 头部的删除
    deletes() {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // console.log(23)
          if (this.multipleSelection.length >= 1) {
            this.$store
              .dispatch('deleteGoodsTypeByIds', this.multipleSelection)
              .then(res => {
                const type = '删除'
                for (let i = 0; i < this.multipleSelection.length; i++) {
                  this.tipformat(
                    res[i],
                    type,
                    this.multipleSelection[i].type_name
                  )
                }
                this.updateChild(this.multipleSelection)
              })
              .catch(err => {
                console.log('批量删除失败', err)
              })
          } else {
            this.$notify({
              title: `至少一条数据`,
              type: 'warning'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>
